package com.example.testrecorder;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testrecorder.domain.ExcelColor;
import com.example.testrecorder.domain.Issue;
import com.example.testrecorder.domain.IssueShowed;
import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.DateUtil;
import com.example.testrecorder.utils.LogUtil;
import com.example.testrecorder.utils.MyDialog;
import com.example.testrecorder.utils.PermissionUtil;
import com.example.testrecorder.utils.WindowUtil;

import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class IssueDetailActivity extends BaseActivity {
    private Toolbar toolbar;
    private TextView idTv,platformTv,frequencyTv,severityTv,solvedTv,proposeTimeTv,updatedTimeTv,titleTv,contentTv,picTv,picTitleTv;
    private ImageView iv;
    private int id;
    private Issue issue;
    private static final String TAG = "IssueDetailActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue_detail);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<Issue> issues = LitePal.where("id=?", "" + id).find(Issue.class);
        if (issues.size()==1){//找到了对应的记录
            issue = issues.get(0);
            idTv.setText(""+id);
            platformTv.setText(issue.getPlatform());
            frequencyTv.setText(issue.getFrequency());
            severityTv.setText(issue.getSeverity());
            solvedTv.setText(issue.getSolved());
            proposeTimeTv.setText(DateUtil.getFormatDateStr(issue.getProposeTime()));
            updatedTimeTv.setText(DateUtil.getFormatDateStr(issue.getUpdateTime()));
            titleTv.setText(issue.getTitle());
            contentTv.setText("问题描述："+issue.getContent());
            showPic(issue);
        }
    }

    private void showPic(Issue issue) {
        Bitmap bitmap = BitmapUtil.getBitmapFromPath(issue.getImgPath());
        if(bitmap!=null){
            LogUtil.logD(TAG,bitmap.toString());
            iv.setImageBitmap(bitmap);
            iv.setVisibility(View.VISIBLE);
        }else {
            picTv.setVisibility(View.VISIBLE);
            picTitleTv.setLayoutParams(new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT,1));//设置权重为1
        }
    }

    private void initView() {
        picTitleTv=findViewById(R.id.picTitleTv);
        picTv=findViewById(R.id.picTv);
        iv=findViewById(R.id.iv);
        idTv=findViewById(R.id.idTv);
        platformTv=findViewById(R.id.platformTv);
        frequencyTv=findViewById(R.id.frequencyTv);
        severityTv=findViewById(R.id.severityTv);
        solvedTv=findViewById(R.id.solvedTv);
        proposeTimeTv=findViewById(R.id.proposeTimeTv);
        updatedTimeTv=findViewById(R.id.updatedTimeTv);
        titleTv=findViewById(R.id.titleTv);
        contentTv=findViewById(R.id.contentTv);
        id = getIntent().getIntExtra("id",-1);
        LogUtil.logD(TAG,"问题的id是："+id);
        toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(IssueDetailActivity.this,MainActivity.class));
            }
        });
        if(Build.VERSION.SDK_INT>=23){
            int i2 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);//写权限包括了读权限
            if(i2!=PackageManager.PERMISSION_GRANTED){//没有授予读写权限
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);//请求读写权限
            }else{//授予了相机权限或读写权限

            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.detail_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.edit:
                Intent intent = new Intent(IssueDetailActivity.this, EditIssueActivity.class);
                intent.putExtra("id",id);
                startActivity(intent);
                break;
            case R.id.export:
                PermissionUtil.reqWriteAndReadPermission(IssueDetailActivity.this, new PermissionUtil.PermittedCallBack() {
                    @Override
                    public void permitted() {
                        exportExcel();
                    }
                },3);
                break;
            case R.id.delete:
                if(issue!=null){
                    MyDialog myDialog=new MyDialog(this);
                    myDialog.setTitle("警告");
                    myDialog.setTitleTextColor("#F17271");
                    myDialog.setContent("您确定要删除标题为“"+issue.getTitle()+"”的记录吗？");
                    myDialog.show();
                    myDialog.setOnNegativeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            myDialog.dismiss();
                        }
                    });
                    myDialog.setOnPositiveListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int delete = LitePal.delete(Issue.class, issue.getId());
                            if(delete>0){
                                Toast.makeText(IssueDetailActivity.this,"删除成功！",Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(IssueDetailActivity.this,MainActivity.class));
                            }else {
                                Toast.makeText(IssueDetailActivity.this,"删除失败！",Toast.LENGTH_SHORT).show();
                            }
                            myDialog.dismiss();
                        }
                    });
                }else {
                    Toast.makeText(IssueDetailActivity.this,"当前的问提为空，删除失败！",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
        return true;
    }

    private void exportExcel() {
        String externalStorageState = Environment.getExternalStorageState();
        if(externalStorageState.equals(Environment.MEDIA_MOUNTED)){//SDK已挂载并且可读写
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            File file=new File(externalStorageDirectory,"TestRecorder");
            if(!file.exists()){
                file.mkdirs();
            }
            if(issue!=null){
                String issueTitle=issue.getTitle();
                String issueDate=DateUtil.getFormatDateStr(issue.getProposeTime());
                File excelFile=new File(file,"测试记录_"+issueTitle+"_"+issueDate+".xls");
                try {
                    if(excelFile.exists()){
                        boolean delete = excelFile.delete();
                        if(delete){
                            LogUtil.logD(TAG,"删除旧文件成功！");
                        }else {
                            LogUtil.logD(TAG,"删除旧文件失败！");
                        }
                    }else {
                        excelFile.createNewFile();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                WritableWorkbook workbook=null;
                try {
                   workbook= Workbook.createWorkbook(excelFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(workbook!=null){
                    WritableSheet sheet = workbook.createSheet("测试记录", 0);
                    String [] arr={"id","平台","发生频率","严重程度","是否已解决","提出时间","修改时间","图片","标题","问题描述"};
                    for (int i = 0; i < arr.length; i++) {
                        String s=arr[i];
                        WritableFont wfc = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.OCEAN_BLUE);
                        WritableCellFormat wcfFC = new WritableCellFormat(wfc);
                        try {
                            wcfFC.setAlignment(Alignment.CENTRE);//水平居中
                            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中
                        } catch (WriteException e) {
                            e.printStackTrace();
                        }
                        Label label=new Label(0,i,s,wcfFC);
                        try {
                            sheet.addCell(label);
                        } catch (WriteException e) {
                            e.printStackTrace();
                        }
                    }
                    WritableFont wfc = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.GRAY_50);
                    WritableCellFormat wcfFC = new WritableCellFormat(wfc);
                    try {
                        wcfFC.setAlignment(Alignment.CENTRE);//水平居中
                        wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中
                    } catch (WriteException e) {
                        e.printStackTrace();
                    }
                    Label label1=new Label(1,0,""+issue.getId(),wcfFC);
                    Label label2=new Label(1,1,issue.getPlatform(),wcfFC);
                    Label label3=new Label(1,2,issue.getFrequency(),wcfFC);
                    Label label4=new Label(1,3,issue.getSeverity(),wcfFC);
                    Label label5=new Label(1,4,issue.getSolved(),wcfFC);
                    Label label6=new Label(1,5,DateUtil.getFormatDateStr(issue.getProposeTime()),wcfFC);
                    Label label7=new Label(1,6,DateUtil.getFormatDateStr(issue.getUpdateTime()),wcfFC);
                    Label label8=new Label(1,8,issue.getTitle(),wcfFC);
                    Label label9=new Label(1,9,issue.getContent(),wcfFC);
                    String imgPath = issue.getImgPath();
                    if(!TextUtils.isEmpty(imgPath)&&imgPath.endsWith(".png")){//jxl只支持添加png格式的图片
                        File f=new File(imgPath);
                        if(f.exists()){
                            WritableImage writableImage=new WritableImage(1,7,1,1,f);
                            sheet.addImage(writableImage);
                        }else {
                            LogUtil.logD(TAG,"路径对应的图片不存在，无法将图片添加到表格中！");
                        }
                    }
                    try {
                        sheet.addCell(label1);
                        sheet.addCell(label2);
                        sheet.addCell(label3);
                        sheet.addCell(label4);
                        sheet.addCell(label5);
                        sheet.addCell(label6);
                        sheet.addCell(label7);
                        sheet.addCell(label8);
                        sheet.addCell(label9);
                    } catch (WriteException e) {
                        e.printStackTrace();
                    }
                    try {
                        workbook.write();
                        MyDialog.showInfo(this,"测试记录导出成功，路径位于"+excelFile.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        workbook.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (WriteException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                Toast.makeText(this, "导出失败，当前的测试记录为空！", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(this, "导出失败，检测出SDK未挂载或者不可读写！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==1){
            if(grantResults.length==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){//如果用户确认授予读写权限
                picTv.setVisibility(View.GONE);
                picTitleTv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, WindowUtil.getPxFromDp(this,40)));//还原“图片”二字的宽度、高度和权重
            }else {
                Toast.makeText(this,"您尚未授予读写文件的权限，将无法显示测试问题的图片。",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode==3){//导出excel文件
            if(grantResults.length==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                exportExcel();
            }else {
                Toast.makeText(this,"您尚未授予读写文件的权限，将无法导出测试记录。",Toast.LENGTH_SHORT).show();
            }
        }
    }
}